#!/usr/bin/env python
# coding=utf-8
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from google.appengine.api import users
from apps.cataccountbook import models
from google.appengine.ext import db
import sys
import appforms

def generate_login_link(back_url):
		user = users.get_current_user()
		if user:
			url = users.create_logout_url(back_url)
			text = 'Logout'
		else:
			url = users.create_login_url(back_url)
			text = 'Login'
		return dict(url=url, text=text)
		
def render(template, payload):
    return render_to_response(template, payload)

def check_user():
    user = users.get_current_user()
    if user:
        return user
    else:
        return HttpResponseRedirect('http://www.google.com.tw')

def index(request):
    payload = dict()
    return render('base.html', payload)

def account_handler(request, action, object_id=''):
    user = users.get_current_user()
    if not user:
        return HttpResponseRedirect(users.create_login_url(request.get_full_path()))

    if action == 'create':
        if request.method == 'POST':
            form = appforms.AccountCustomForm(data=request.POST)
            if form.is_valid():        
                data = form.clean_data.copy()
                data['user'] = user
                data['initialValue'] = float(data['initialValue'])
                data['accountType'] = int(data['accountType'])
                account = models.Account(user=data['user'], name=data['name'], initialValue=data['initialValue'], accountType=data['accountType'], note=data['note'])
                account.put()
            else:
                errors = form.errors
                payload = dict( errors=errors)
                return render('error.html', payload)
        else:
            cform = appforms.AccountCustomForm()
            payload = dict(action=action, cform=cform, object_id='')
            return render('form_account.html', payload)
    elif action == 'edit':
        instance = db.get(object_id)
        if instance and (users.is_current_user_admin() or instance.user == user):
            if request.method == 'POST':
                form = appforms.AccountCustomForm(data=request.POST)
                if form.is_valid():
                    data = form.clean_data.copy()
                    instance.name = data['name']
                    instance.initialValue = float(data['initialValue'])
                    instance.accountType = int(data['accountType'])
                    instance.note = data['note']
                    instance.put()
                else:
                    errors = form.errors
                    payload = dict( errors=errors)
                    return render('error.html', payload)
            else:
                data = dict(
                    name=instance.name,
                    initialValue=instance.initialValue,
                    accountType=instance.accountType
                    )
                cform = appforms.AccountCustomForm(data=data)
                payload = dict(action=action, cform=cform, object_id=object_id)
                return render('form_account.html', payload)
    elif action == 'delete':
        instance = db.get(object_id)
        if instance and (users.is_current_user_admin() or instance.user == user):
            account_delete(instance)
    elif action == 'get':
        instance = db.get(object_id)
        if instance and (users.is_current_user_admin() or instance.user == user):
            payload = dict(action=action, instance=instance)
            return render('form_account.html', payload)
    
    return HttpResponseRedirect('/debug/')

def category_handler(request, action, object_id=0):
    user = users.get_current_user()
    if not user:
        return HttpResponseRedirect(users.create_login_url(request.get_full_path()))

    if action == 'create':
        if request.method == 'POST':
            form = appforms.CategoryCustomForm(data=request.POST)
            if form.is_valid():
                data = form.clean_data.copy()
                data['user'] = user
                category = models.Category(user=data['user'], name=data['name'], order=data['order'], note=data['note'])
                category.put()
            else:
                errors = form.errors
                payload = dict( errors=errors)
                return render('error.html', payload)
        else:
            cform = appforms.CategoryCustomForm()
            payload = dict(action=action, cform=cform, object_id='')
            return render('form_category.html', payload)                        
    elif action == 'edit':
        instance = db.get(object_id)
        if instance and (users.is_current_user_admin() or instance.user == user):
            if request.method == 'POST':
                form = appforms.CategoryCustomForm(data=request.POST)
                if form.is_valid():
                    data = form.clean_data.copy()
                    instance.name = data['name']
                    instance.order = data['order']
                    instance.note = data['note']
                    instance.put()
                else:
                    errors = form.errors
                    payload = dict( errors=errors)
                    return render('error.html', payload)
            else:
                data = dict(
                    name=instance.name,
                    order=instance.order,
                    note=instance.note
                    )
                cform = appforms.CategoryCustomForm(data=data)
                payload = dict(action=action, cform=cform, object_id=object_id)
                return render('form_category.html', payload)
    elif action == 'delete':
        instance = db.get(object_id)
        if instance and (users.is_current_user_admin() or instance.user == user):
            category_delete(instance)
    elif action == 'get':
        instance = db.get(object_id)
        if instance and (users.is_current_user_admin() or instance.user == user):
            payload = dict(action=action, instance=instance)
            return render('form_category.html', payload)
    
    return HttpResponseRedirect('/debug/')            

def record_handler(request, action, object_id=0):
    user = users.get_current_user()
    if not user:
        return HttpResponseRedirect(users.create_login_url(request.get_full_path()))
                
    if action == 'create':
        if request.method == 'POST':
            form = appforms.RecordCustomForm(user=user, data=request.POST)
            if form.is_valid():
                data = form.clean_data.copy()
                data['account'] = models.Account.get(data['account_key'])
                data['action'] = int(data['action'])
                data['value'] = float(data['value'])
                if data['category_key'] != '':
                    data['category'] = models.Category.get(data['category_key'])
                else:
                    data['category'] = None
                record = models.Record(
                    account=data['account'], 
                    action=data['action'], 
                    value=data['value'],
                    recordDate=data['recordDate'],
                    reason=data['reason'],
                    category=data['category'],
                    note=data['note'],
                    )               
                record.put()
            else:
                errors = form.errors
                payload = dict(errors=errors)
                return render('error.html', payload)          
        else:
            cform = appforms.RecordCustomForm(user)           
            payload = dict(action=action, cform=cform, object_id='')
            return render('form_record.html', payload)
    elif action == 'edit':
        instance = db.get(object_id)
        account = models.Account.get(instance.account.key())
        if instance and (users.is_current_user_admin() or account.user == user):
            if request.method == 'POST':
                form = appforms.RecordCustomForm(user=user, data=request.POST)
                if form.is_valid():
                    data = form.clean_data.copy()
                    data['account'] = models.Account.get(data['account_key'])
                    data['action'] = int(data['action'])
                    data['value'] = float(data['value'])
                    if data['category_key'] != '':
                        data['category'] = models.Category.get(data['category_key'])
                    else:
                        data['category'] = None    
                    instance.account=data['account']
                    instance.action=data['action']
                    instance.value=data['value']
                    instance.recordDate=data['recordDate']
                    instance.reason=data['reason']
                    instance.category=data['category']
                    instance.note=data['note']                 
                    instance.put()
                else:
                    errors = form.errors
                    payload = dict( errors=errors)
                    return render('error.html', payload)
            else:
                data = dict(
                    account_key=instance.account.key(), 
                    action=instance.action, 
                    value=instance.value,
                    recordDate=instance.recordDate,
                    reason=instance.reason,
                    note=instance.note,
                    )
                if instance.category != None:
                    data['category_key'] = instance.category.key()
                cform = appforms.RecordCustomForm(user=user, data=data)
                payload = dict(action=action, cform=cform, object_id=object_id)
                return render('form_record.html', payload)
    elif action == 'delete':
        instance = db.get(object_id)
        if instance and (users.is_current_user_admin() or instance.user == user):
            record_delete(instance)
    elif action == 'get':
        instance = db.get(object_id)
        if instance and (users.is_current_user_admin() or instance.user == user):
            payload = dict(action=action, instance=instance)
            return render('form_record.html', payload)

    return HttpResponseRedirect('/debug/')

def transaction_handler(request, action, object_id=0):
    user = users.get_current_user()
    if not user:
        return HttpResponseRedirect(users.create_login_url(request.get_full_path()))

    if action == 'create':
        if request.method == 'POST':
            form = appforms.TransactionCustomForm(user=user, data=request.POST)
            if form.is_valid():
                data = form.clean_data.copy()
                data['source_account'] = models.Account.get(data['source_account_key'])
                data['destination_account'] = models.Account.get(data['destination_account_key'])
                if data['category_key'] != '':
                    data['category'] = models.Category.get(data['category_key'])
                else:
                    data['category'] = None  
                data['value'] = float(data['value'])
                #轉入
                record = models.Record(
                    account=data['source_account'], 
                    action=3, 
                    value=data['value'],
                    recordDate=data['recordDate'],
                    reason=data['reason'],
                    category=data['category'],
                    note=data['note'],
                    )
                source_record_key = record.put()
                data['source_record'] = models.Record.get(source_record_key)
                #轉出
                record = models.Record(
                    account=data['destination_account'], 
                    action=4, 
                    value=-data['value'],
                    recordDate=data['recordDate'],
                    reason=data['reason'],
                    category=data['category'],
                    note=data['note'],
                    )
                destination_record_key = record.put()
                data['destination_record'] = models.Record.get(destination_record_key)    
                transaction = models.Transaction(
                    user = user,
                    sourceAccount = data['source_account'],
                    sourceRecord = data['source_record'],
                    destinationAccount = data['destination_account'],
                    destinationRecord = data['destination_record']
                    )
                transaction.put()
            else:
                errors = form.errors
                payload = dict(errors=errors)
                return render('error.html', payload)          
        else:
            cform = appforms.TransactionCustomForm(user)           
            payload = dict(action=action, cform=cform, object_id='')
            return render('form_transaction.html', payload)
    elif action == 'edit':
        instance = db.get(object_id)
        if instance and (users.is_current_user_admin() or instance.user == user):
            if request.method == 'POST':
                form = appforms.AcountForm(data=request.POST, instance=instance)
                form.save()
            else:
                form = appforms.TransactionForm(instance=instance)
                payload = dict(action=action, form=form)
            return render('form_transaction.html', payload)
    elif action == 'delete':
        instance = db.get(object_id)
        if instance and (users.is_current_user_admin() or instance.user == user):
            transaction_delete(instance)
    elif action == 'get':
        instance = db.get(object_id)
        if instance and (users.is_current_user_admin() or instance.user == user):
            payload = dict(action=action, instance=instance)
            return render('form_transaction.html', payload)

    return HttpResponseRedirect('/debug/')
    
def account_delete(instance):
    records = models.Record.all().filter('account = ', instance)
    for record in records:
        record_delete(record)
    return instance.delete()

def category_delete(instance):
    records = models.Record.all().filter('category = ', instance)
    for record in records:
        record.category = None
        record.put()
    return instance.delete()

# 這是用於 account 刪除時的階層式處理
def record_delete(instance):
    # 如果把轉出紀錄刪除, 那轉入紀錄會變成收入
    transactions = models.Transaction.all().filter('sourceRecord = ', instance)
    for transaction in transactions:
        transaction.destinationRecord.action = 1
        transaction.destinationRecord.put()
        transaction.delete()
    # 如果把轉入紀錄刪除, 那轉出紀錄會變成支出
    transactions = models.Transaction.all().filter('destinationRecord = ', instance)
    for transaction in transactions:
        transaction.sourceRecord.action = 2
        transaction.sourceRecord.put()
        transaction.delete()
    return instance.delete()

# 刪除轉移紀錄, 要把轉出與轉錄都刪除
def transaction_delete(instance):
    instance.sourceRecord.delete()
    instance.destinationRecord.delete()
    instance.delete()

def debug(request):
    user = users.get_current_user()
    if not user:
        return HttpResponseRedirect(users.create_login_url(request.get_full_path()))

    accounts = models.Account.all()
    categories = models.Category.all()
    records = models.Record.all()
    transactions = models.Transaction.all()
    
    link = generate_login_link(request.get_full_path())
    payload = dict(accounts=accounts, categories=categories, records=records, transactions=transactions, login_url=link['url'], login_text=link['text'])
    return render('debug.html', payload)
